//
//  MLSNetworkTool.swift
//  MLSMircoBlog
//
//  Created by 袁航 on 15/7/29.
//  Copyright © 2015年 yuanhang. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
///  错误domain
let userDomain: String = "com.yuanhang.requestGET"
/// 请求方法类型
private enum MLSMethodType: String {
    case POST = "POST"
    case GET = "GET"
}
/// 错误返回
private enum netWorkError: Int {
    case netWorkDataError = -1
    case netWorkTokenError = -2
    
    /// 错误描述
    private var errorDescription: String {
        switch self {
        case .netWorkDataError: return "空数据"
        case .netWorkTokenError: return "token错误"
        }
    }
    /// 返回错误
    private func error() -> NSError {
        return NSError(domain: userDomain, code: rawValue, userInfo: [userDomain:errorDescription])
    }
}
class MLSNetworkTool: AFHTTPSessionManager {
    // MARK:- 属性
    /// 客户端id
    private let clientId = "2232467256"
    /// 回调网址URL
    let redirectUri = "http://www.baidu.com"
    /// 授权安全信息
    private let appSecret = "5409ee6fdfe31da3cadcc97f6911235c"
    
    
    //MARK:- 跟用户相关的获取授权&获取用户信息
    
    //MARK:- 注册按钮网址
    func regesterURL() -> NSURL {
        return NSURL(string: "http://m.weibo.cn/reg/index")!
    }
    
    //MARK:- 授权处理(自定义函数)
    //MARK: 返回请求授权URL,用来请求用户授权Token
    func oauthURL() -> NSURL {
        return NSURL(string:"https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)")!
    }
    
    //MARK: 获取授权  获取授权过的Access Token  注意要用? 表示可变
    func accessToken(code: String, finshed: MLSNetworkingFinishedClosure) {
        // 准备URL
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        // 根据文档准备参数
        let param = ["client_id":clientId,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUri,]
        
        // 发送POST请求
        request(MLSMethodType.POST, urlString: urlStr, parameters: param, finished: finshed)
    }
    // MARK:- 获取用户token
    private func loadUserToken(finshed:MLSNetworkingFinishedClosure) -> [String: AnyObject]? {
        
        if MLSAccessToken.shareAccessToken?.access_token == nil{
            finshed(nil, netWorkError.netWorkTokenError.error())
            return nil
        }
        return ["access_token": MLSAccessToken.shareAccessToken!.access_token!]
    }

    // MARK:- 加载用户信息
    func loadUserAccountInfo(uid: String, finshed: MLSNetworkingFinishedClosure){
    /// 守卫parmas,当params为空的时候,进入else语句. 不为空,就执行下面的语句
        guard var params = loadUserToken(finshed) else {
            return
        }
        let urlStr = "2/users/show.json"
        // 增加参数
        params["uid"] = uid
        // 自定义get请求,请求用户信息
        request(MLSMethodType.GET, urlString: urlStr, parameters: params, finished: finshed)
    }
    
    // MARK:- 加载微博数据
    // - 根据 since_id 则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    // max_id 则返回ID小于或等于max_id的微博，默认为0。
    ///  加载微博数据(附带刷新功能)
    ///
    ///  - parameter since_id: 刷新新的微博的id(默认为0)
    ///  - parameter max_id  : 刷新旧微博的id(默认为0)
    ///  - parameter finshed : 结束回调
    func loadStatus(since_id: Int, max_id: Int, finshed: MLSNetworkingFinishedClosure) {
        
        guard var params = loadUserToken(finshed) else {
            // 提示授权过期
            SVProgressHUD.showErrorWithStatus("授权过期")
            return
        }
        if since_id > 0 {
            params["since_id"] = since_id
        }
        if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        let urlStr = "2/statuses/friends_timeline.json"
        // 发送请求
        request(MLSMethodType.GET, urlString: urlStr, parameters: params, finished: finshed)
        
    }
    //MARK:TODO- 发送微博
    //access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
    func sendStatus(status: String, finshed: MLSNetworkingFinishedClosure) {
        
        guard var params = loadUserToken(finshed) else {
            SVProgressHUD.showErrorWithStatus("授权过期")
            return
        }
        params["status"] = status
        
        request(MLSMethodType.POST, urlString: "2/statuses/update.json", parameters: params, finished: finshed)
    }
    
    //MARK:- swift网络单例
    static let sharNewworkTools: MLSNetworkTool = {
        let basUrl = NSURL(string: "https://api.weibo.com/")
        // 实例化单例对象
        let instance = MLSNetworkTool(baseURL: basUrl)
        // 设置解析类型
        instance.responseSerializer.acceptableContentTypes = NSSet(objects:"application/json", "text/json", "text/javascript","text/plain") as Set<NSObject>
        return instance
        }()

    // MARK:- 封装AFN的get和post请求,降低耦合度
    /// 自定义闭包类型
    typealias MLSNetworkingFinishedClosure = ([String: AnyObject]?, NSError?)->()

    // 封装get和post请求为一个方法
    private func request(requestMethod: MLSMethodType, urlString: String, parameters: [String: AnyObject], finished: MLSNetworkingFinishedClosure){
        // 定义成功回调闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) -> Void = {  (_, JSON) -> Void in
            
            // 如果返回数据不为空,调用成功回调
            if let result = JSON as? [String: AnyObject] {
                finished(result, nil)
            } else {
                ///  调用失败回调
                finished(nil, netWorkError.netWorkDataError.error())
            }
            
        }
        // 定义失败回调闭包
        let errorCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            // 失败回调
            finished(nil, error)
        }
        
        // 查看方法类型
        switch requestMethod {
        case .GET:
            GET(urlString, parameters: parameters, success: successCallBack, failure: errorCallBack)
        case .POST:
            POST(urlString, parameters: parameters, success: successCallBack, failure: errorCallBack)

        }
    }
}
